<?php

namespace app\api\controller\v33;


use app\api\controller\v13\Auth2;
use app\common\cachemodel\AppBlacklist;
use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\zl1_relation\Zl1AstrCommunityArticle;
use app\common\cachemodel\zl1_relation\Zl1AstrCommunityArticleZan;
use app\common\cachemodel\zl1_relation\Zl1RelationTag;
use app\common\cachemodel\zl1_relation\Zl1RelationText;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\Article as ArticleModel;
use app\common\model\Recode;
use app\common\model\User;
use think\Cache;
use think\response\Json;

/**
 * Class AstrCommunity 星座社区
 * @package app\api\controller\v33
 */
class AstrCommunity extends Auth2
{
    protected $inSignNames = [
        1 => '白羊座',
        2 => '金牛座',
        3 => '双子座',
        4 => '巨蟹座',
        5 => '狮子座',
        6 => '处女座',
        7 => '天秤座',
        8 => '天蝎座',
        9 => '射手座',
        10 => '摩羯座',
        11 => '水瓶座',
        12 => '双鱼座',
    ];

    /**
     * 获取星座及标签类型
     * @return Json
     */
    public function getAstrAndRelation()
    {
        $relationList = (new Zl1RelationTag())->getRelationTag(0, ['id', 'name']);

        $relationData = [];
        foreach ($relationList as $relationItem)
        {
            $relationData[] = [
                'id' => $relationItem['id'],
                'name' => $relationItem['name'],
            ];
        }

        $resData = [
            'sign' => [
                [
                    'id' => 1,
                    'name' => '白羊座',
                ],
                [
                    'id' => 2,
                    'name' => '金牛座',
                ],
                [
                    'id' => 3,
                    'name' => '双子座',
                ],
                [
                    'id' => 4,
                    'name' => '巨蟹座',
                ],
                [
                    'id' => 5,
                    'name' => '狮子座',
                ],
                [
                    'id' => 6,
                    'name' => '处女座',
                ],
                [
                    'id' => 7,
                    'name' => '天秤座',
                ],
                [
                    'id' => 8,
                    'name' => '天蝎座',
                ],
                [
                    'id' => 9,
                    'name' => '射手座',
                ],
                [
                    'id' => 10,
                    'name' => '摩羯座',
                ],
                [
                    'id' => 11,
                    'name' => '水瓶座',
                ],
                [
                    'id' => 12,
                    'name' => '双鱼座',
                ],
            ],
            'relation' => $relationData,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取星座关系介绍
     */
    public function getAstrRelationIntro()
    {
        $inSign = input('in_sign/d', 0);

        if (!in_array($inSign, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
        {
            if ($this->user && $this->user['rid'])
            {
                $recode = (new \app\common\cachemodel\Recode())->getInfoById($this->user['rid']);
                if ($recode)
                {
                    $inSign = (int)(explode('-', $recode['sun'])[0]);
                } else
                {
                    $inSign = 1;//  未登录 ｜ 没有档案 且没有传星座信息  默认 白羊座
                }
            } else
            {
                $inSign = 1;//  未登录 ｜ 没有档案 且没有传星座信息  默认 白羊座
            }
        }

        $resData = [
            'in_sign' => $inSign,
            'overall' => [],
            'relation' => [],
            'week' => null,
        ];
        // 获取星座 关系 信息
        $textData = (new Zl1RelationText())->getRelationTextList($inSign);

        $resData['overall'] = $textData[1];
        $resData['relation'] = $textData[2];

        // 周运
        $week = (new ArticleModel())->getFortune('week', $inSign);
        $week['time_range'] = date('Y.m.d', strtotime($week['publish_time'])) . '-' . date('Y.m.d', strtotime($week['publish_time'] . ' +6 day'));

        $resData['week'] = [
            'title' => $week['introduction'],
            'introduction' => $week['time_range'],
            'content' => $week['content'],
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 星座讨论
     * @return Json
     * @throws ApiException
     * @throws \Exception
     */
    public function getArticle()
    {
        $inSigns = input('in_signs/s', '');
        $relationIds = input('relation_ids/s', '');
        $page = input('page/d', 1);

        $inSignsArr = $inSigns ? array_filter(array_map('intval', explode(',', $inSigns))) : [];
        $relationIdsArr = $relationIds ? array_filter(array_map('intval', explode(',', $relationIds))) : [];
        $astrCommunityArticleModel = new Zl1AstrCommunityArticle();
        $uid = $this->user ? $this->user['id'] : 0;

        $articlePages = $astrCommunityArticleModel->getArticleIds($inSignsArr, $relationIdsArr);

        $relationList = (new Zl1RelationTag())->getRelationTag(0, ['id', 'name']);

        if ($articlePages['data'])
        {
            $ids = array_column($articlePages['data'], 'id');

            $datas = $astrCommunityArticleModel->batchGetInfoByIds($ids, []);

            $astrCommunityArticleZanModel = new Zl1AstrCommunityArticleZan();

            $zanData = $uid > 0 ? $astrCommunityArticleZanModel->getZan($uid, $ids) : [];

            if ($zanData)
            {
                if (count($ids) === 1 && !is_array($zanData))
                {
                    $zanData = [current($ids) => (int)$zanData];
                }
            }
            // 取 黑名单用户uid   ----------------------------------------------------------------
            $blacklistUids = (new AppBlacklist())->getBlacklistUids($this->user['id']);

            $resData = [];
            $userInfoList = [];
            foreach ($articlePages['data'] as $datum)
            {
                $d = $datas[$datum['id']];
                if (in_array($d['uid'], $blacklistUids, true))
                {   // 过滤 黑名单 用户
                    continue;
                }
                $userDes = '小行星神秘人';
                if (isset($userInfoList[$d['uid']]))
                {
                    $userDes = $userInfoList[$d['uid']]['user_des'];
                    $nickname = $userInfoList[$d['uid']]['nickname'];
                    $avatar = $userInfoList[$d['uid']]['avatar'];
                } else
                {
                    try
                    {
                        $userInfo = (new User())->getUserinfo(['id' => $d['uid']]);
                    }
                    catch (\Exception $e)
                    {
                        continue;
                    }
                    if ($userInfo['rid'])
                    {
                        $recode = (new Recode())->getRecode(['id' => $userInfo['rid']]);
                        if ($recode)
                        {
                            $utilModel = new Util();
                            $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                        }
                    }
                    $nickname = $userInfo['nickname'];
                    $avatar = $userInfo['avatar'];
                    $userInfoList[$d['uid']] = [
                        'nickname' => $nickname,
                        'avatar' => $avatar,
                        'user_des' => $userDes,
                    ];
                }
                $adorn = Util::getUserAdorn($d['uid']);

                $commentBase = $d['extend']['comment_base'] ?? 0;
                $zanBase = $d['extend']['zan_base'] ?? 0;
                $zan2Base = $d['extend']['zan2_base'] ?? 0;

                $resData[] = [
                    'id' => $d['id'],
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'create_time' => Util::timeToStr($d['create_time']),
                    'user_des' => $userDes,
                    'title' => $d['title'],
                    'comment_num' => $d['comment_num'] + $commentBase,
                    'photo_list' => $d['photos'],
                    'isself' => $d['uid'] === $uid ? 1 : 0,
                    'avatar_adorn' => $adorn['avatar_adorn'],
                    'tag' => $adorn['tag'],
                    'badge' => $adorn['badge'],
                    'sign_name' => $this->inSignNames[$d['in_sign']],
                    'relation_name' => $d['relation_id'] > 0 ? $relationList[$d['relation_id']]['name'] : '',
                    'in_sign' => $d['in_sign'],
                    'relation_id' => $d['relation_id'],
                    'zan_num' => $d['zan_num'] + $zanBase,
                    'zan_num2' => $d['zan_num2'] + $zan2Base,
                    'is_zan' => isset($zanData[$d['id']]) && $zanData[$d['id']] ? (int)$zanData[$d['id']] : 0,  // 赞同｜反对
                ];
            }

            $articlePages['data'] = $resData;
        }

        $tabs = null;
        if ($page === 1)
        {
            $cacheKey = 'astr_community:tab:' . ($uid && $this->user['rid'] ? $uid : 0);
            $tabs = Cache::get($cacheKey, false);
            if (!$tabs)
            {
                $tabs = [
                    [
                        'title' => '全部',
                        'in_sign' => 0,
                        'relation_id' => 0,
                    ],
                ];
                $inSignIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
                shuffle($inSignIds);
                if ($this->user && $this->user['rid'])
                {
                    $recode = (new Recode())->getRecode(['id' => $this->user['rid']]);
                    $selfInSign = (int)(explode('-', $recode['sun'])[0]);
                    $sexRelationId = (int)$recode['type'] === 2 ? 9 : 8;
                    $tabs[] = [
                        'title' => $this->inSignNames[$selfInSign] . $relationList[$sexRelationId]['name'],
                        'in_sign' => $selfInSign,
                        'relation_id' => $sexRelationId,
                    ];
                    $relationId2 = $sexRelationId === 9 ? 8 : 9;
                    $inSign2 = array_pop($inSignIds);
                    $tabs[] = [
                        'title' => $this->inSignNames[$inSign2] . $relationList[$relationId2]['name'],
                        'in_sign' => $inSign2,
                        'relation_id' => $relationId2,
                    ];
                } else
                {
                    $inSign1 = array_pop($inSignIds);
                    $relationId1 = random_int(8, 9);
                    $tabs[] = [
                        'title' => $this->inSignNames[$inSign1] . $relationList[$relationId1]['name'],
                        'in_sign' => $inSign1,
                        'relation_id' => $relationId1,
                    ];
                    $relationId2 = $relationId1 === 9 ? 8 : 9;
                    $inSign2 = array_pop($inSignIds);
                    $tabs[] = [
                        'title' => $this->inSignNames[$inSign2] . $relationList[$relationId2]['name'],
                        'in_sign' => $inSign2,
                        'relation_id' => $relationId2,
                    ];
                }
                $inSign3 = array_pop($inSignIds);
                $tabs[] = [
                    'title' => $this->inSignNames[$inSign3] . $relationList[7]['name'],
                    'in_sign' => $inSign3,
                    'relation_id' => 7,
                ];
                $inSign4 = array_pop($inSignIds);
                $tabs[] = [
                    'title' => $this->inSignNames[$inSign4] . $relationList[2]['name'],
                    'in_sign' => $inSign4,
                    'relation_id' => 2,
                ];
                $inSign5 = array_pop($inSignIds);
                $tabs[] = [
                    'title' => $this->inSignNames[$inSign5] . $relationList[6]['name'],
                    'in_sign' => $inSign5,
                    'relation_id' => 6,
                ];
                $inSign6 = array_pop($inSignIds);
                $tabs[] = [
                    'title' => $this->inSignNames[$inSign6] . $relationList[3]['name'],
                    'in_sign' => $inSign6,
                    'relation_id' => 3,
                ];

                Cache::set($cacheKey, $tabs, 43200);
            }
        }

        $returnData = [
            'tabs' => $tabs,
            'data' => $articlePages,
        ];

        return show(config('code.success'), '请求成功', $returnData);
    }

    /**
     * 星座讨论详情
     */
    public function getArticleDetail()
    {
        $id = input('id/d', 0);
        $page = input('page/d', 1);
        $uid = $this->user ? $this->user['id'] : 0;

        if ($id < 1)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $resData['article_info'] = null;
        $articleDetail = null;
        $astrCommunityArticleModel = new Zl1AstrCommunityArticle();

        if ($page === 1)
        {
            $articleDetail = $astrCommunityArticleModel->getInfoById($id);

            if ($articleDetail['uid'] === $uid)
            {
                $nickname = $this->user['nickname'] ?? '';
                $avatar = $this->user['avatar'] ?? '';
                $rid = $this->user['rid'] ?? 0;
                $isSelf = 1;
            } else
            {
                $userInfo = (new User())->getUserinfo(['id' => $articleDetail['uid']]);
                $nickname = $userInfo['nickname'] ?? '';
                $avatar = $userInfo['avatar'] ?? '';
                $rid = $userInfo['rid'] ?? 0;
                $isSelf = 0;
            }

            $userDes = '小行星神秘人';
            if ($rid)
            {
                $recode = (new Recode())->getRecode(['id' => $rid]);
                if ($recode)
                {
                    $utilModel = new Util();
                    $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                }
            }
            $relationList = (new Zl1RelationTag())->getInfoById($articleDetail['relation_id'], ['id', 'name']);
            // 获取装饰信息
            $adorn = Util::getUserAdorn($articleDetail['uid']);

            $astrCommunityArticleZanModel = new Zl1AstrCommunityArticleZan();
            // 获取用户当前 已赞同 1/已反对 2
            $zanData = $uid > 0 ? $astrCommunityArticleZanModel->getZan($uid, [$id]) : [];

            if ($zanData && !is_array($zanData))
            {
                $zanData = [$id => (int)$zanData];
            }

            $commentBase = $articleDetail['extend']['comment_base'] ?? 0;
            $zanBase = $articleDetail['extend']['zan_base'] ?? 0;
            $zan2Base = $articleDetail['extend']['zan2_base'] ?? 0;

            $resData['article_info'] = [
                'nickname' => $nickname,
                'avatar' => $avatar,
                'user_des' => $userDes,
                'create_time' => Util::timeToStr($articleDetail['create_time']),
                'title' => $articleDetail['title'],
                'comment_num' => $articleDetail['comment_num'] + $commentBase,
                'photo_list' => $articleDetail['photos'],
                'isself' => $isSelf,
                'author_id' => $articleDetail['uid'],
                'avatar_adorn' => $adorn['avatar_adorn'],
                'tag' => $adorn['tag'],
                'badge' => $adorn['badge'],
                'zan_num' => $articleDetail['zan_num'] + $zanBase,
                'zan_num2' => $articleDetail['zan_num2'] + $zan2Base,
                'is_zan' => isset($zanData[$id]) && $zanData[$id] ? (int)$zanData[$id] : 0,  // 赞同｜反对
                'sign_name' => $this->inSignNames[$articleDetail['in_sign']],
                'relation_name' => $articleDetail['relation_id'] > 0 ? $relationList['name'] : '',
            ];
            // 阅读数 新增
            $astrCommunityArticleModel->changeArticleInfo([
                'id' => $id,
                'read_num' => $articleDetail['read_num'],
                'comment_num' => $articleDetail['comment_num'],
            ], 1, 1);
        }

        $articleCommentModel = new ArticleComment();
        // 获取用户评论列表信息
        $commentData = $articleCommentModel->getPageCommentList($uid, 5, $id, 2, $page);

        foreach ($commentData['data'] as $key => $item)
        {
            $commentData['data'][$key]['create_time'] = $item['time'];
        }

        $resData = array_merge($resData, $commentData);

        if ($articleDetail && isset($articleDetail['comment_num']) && $commentData['total'] !== $articleDetail['comment_num'])
        {
            if ($page === 1)
            {
                $resData['article_info']['comment_num'] = $commentData['total'];
            }

            $astrCommunityArticleModel->UpdateData($id, ['comment_num' => $commentData['total']]);
        }

        return show(config('code.success'), '请求成功', $resData);
    }

}
